<template>
  <component :is="currentLoginComponent" @login="handleLoginSuccess" />
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getLoginComponent, getDefaultLoginComponent } from '@/components/auth/login/index.js'

const router = useRouter()
const route = useRoute()

// 获取用户配置的登录样式
const getUserLoginStyle = () => {
  // 如果是预览模式，优先使用URL参数中的样式
  if (route.query.preview === 'true' && route.query.style) {
    return route.query.style
  }
  
  // 否则从本地存储读取用户配置
  try {
    const savedInterfaceSettings = localStorage.getItem('interfaceSettings')
    if (savedInterfaceSettings) {
      const settings = JSON.parse(savedInterfaceSettings)
      return settings.loginStyle || getDefaultLoginComponent()
    }
  } catch (error) {
    console.error('加载登录样式配置失败:', error)
  }
  return getDefaultLoginComponent()
}

// 动态加载登录组件
const loginStyle = ref(getUserLoginStyle())

// 监听URL参数变化（预览模式）
watch(() => route.query.style, (newStyle) => {
  if (route.query.preview === 'true' && newStyle) {
    loginStyle.value = newStyle
  }
})

const currentLoginComponent = computed(() => {
  return getLoginComponent(loginStyle.value)
})

// 处理登录成功事件
const handleLoginSuccess = (response) => {
  // 预览模式下不进行跳转
  if (route.query.preview === 'true') {
    return
  }
  
  // 获取重定向路径
  const redirect = route.query.redirect
  
  // 如果有重定向路径，跳转到该路径，否则跳转到 dashboard
  if (redirect && redirect !== '/login') {
    router.push(decodeURIComponent(redirect))
  } else {
    router.push('/dashboard')
  }
}
</script>
